package com.region.integral.common_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.common_user.obtain.dao.IIntegralJoinGroup;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.CUIEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.JoinGroup;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.XMLRegulationUtil;
@Component("iJoinGroup")
public class IntegralJoinGroupImpl extends BaseHibernate implements IIntegralJoinGroup {

	@Override
	public void joinGroup(int userid,IntegralData integralData)throws IntegralException {
		CUIEntity cuiEntity = getCUIEntity(userid);
		if (cuiEntity != null) {
			int joinGroupNum = cuiEntity.getJoinGroupNum();
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<JoinGroup> joinGroups = regulation.getJoingroup();
			for (JoinGroup joinGroup : joinGroups) {
				if (joinGroupNum % joinGroup.getRate() == 0) {
					int currIntegral = cuiEntity.getCurrIntegral();
					int maxIntegral = cuiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ joinGroup.getIntegral();
					cuiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					
					integralData.setSuccee(true);
					integralData.setObtainIntegral(joinGroup.getIntegral());
					
				}
				cuiEntity.setJoinGroupNum(joinGroupNum+1);
				hibernateTemplate.update(cuiEntity);
			}
		}
	}

}
